# -*- coding: utf-8 -*-
import base64

import cv2
import datetime
import numpy as npy

from face_recognition.service.face_info_service import FaceInfoService
from face_recognition.service.user_info_service import UserInfoService
from face_recognition.utils.array_utils import ListTools
from face_recognition.utils.log_utils import LoggerUtil
from face_recognition.utils.pickle_utils import PickleUtil


class ModelManager:
	
	def __init__(self):
		self.face_info_service = FaceInfoService()
		self.user_info_service = UserInfoService()
		self.recognizer = cv2.face.LBPHFaceRecognizer_create()
	
	def load_model(self):
		"""
		利用已经存储的人脸特征信息或者人脸图片，训练人脸训练模型
		:return:
		"""
		if self.recognizer is None:
			self.recognizer = cv2.face.LBPHFaceRecognizer_create()
		self.recognizer = PickleUtil.restore_recognition_model(self.recognizer)
		return self.recognizer
	
	def train(self, train_faces, train_face_labels):
		"""
		利用已经存储的人脸特征信息或者人脸图片，训练人脸训练模型
		:return:
		"""
		if self.recognizer is None:
			self.recognizer = cv2.face.LBPHFaceRecognizer_create()
		if ListTools.isNotEmpty(train_faces) and ListTools.isNotEmpty(train_face_labels):
			start_time = datetime.datetime.now()
			train_face_labels_array = npy.array(train_face_labels)
			self.recognizer.train(train_faces, train_face_labels_array)
			time_diff = datetime.datetime.now() - start_time
			LoggerUtil.info("训练完成，持久化")
			PickleUtil.dump_recognition_model(self.recognizer)
			LoggerUtil.info("训练数据：" + str(time_diff) + "秒")
			return self.recognizer
		else:
			LoggerUtil.info("训练数据为空，或者暂无人脸图像，不需要进行训练！")
